from flask import render_template

import app.dao.dao as dao
from app.utils import log


class User_DAO(dao.DAO):
    # 实现单例
    _instance = None

    def __new__(cls, *args, **kwargs):
        if not cls._instance:
            cls._instance = super().__new__(cls)

        return cls._instance

    def __init__(self):
        self.logger= log.Logger(__name__)
        super().__init__()

        # config_reader = ConfigReader()
        # self.data_base = config_reader.get_value('database_dev', 'database')
        # self.usr_name = config_reader.get_value('database_dev', 'username')
        # self.usr_pwd = config_reader.get_value('database_dev', 'userpwd')

    def do_login(self, user_name, password):

        sql = 'select usr_id from usr_login where usr_account = \'%s\' and usr_passwd = \'%s\'' % (user_name, password)
        values = self.execute_query(sql)
        # 如果大于一条记录，说明数据库出错
        if len(values) > 1:
            self.logger.critical('数据库出错，usr_account=%s, usr_passwd=%s' % (user_name, password))
            return None
        if len(values)==0:
            self.logger.critical('用户不存在，usr_account=%s, usr_passwd=%s' % (user_name, password))
            return None
        return values

    #用户注册
    def do_register(self, usr):
    #首先检查用户是否存在
        sql = 'select usr_id from usr_login where usr_account = \'%s\'' % usr.usr_account
        values = self.execute_query(sql)
        print("values.length="+str(len(values)))
        if len(values) > 0:
            self.logger.critical('用户已存在，usr_account=%s' % (usr.usr_account))
            return render_template('register.html', error='用户已存在')
        #插入用户信息
        sql = 'insert into usr_login(usr_account,usr_passwd) values(\'%s\',\'%s\')' % (usr.usr_account, usr.usr_password)
        self.execute_insert(sql)
        #提交事务
        #获取用户id
        sql = 'select usr_id from usr_login where usr_account = \'%s\'' % (usr.usr_account)
        values = self.execute_query(sql)
        print("values.length="+str(len(values)))

        if len(values) > 1:
            self.logger.critical('数据库出错，usr_account=%s' % (usr.usr_account))
            return render_template('register.html', error='数据库出错')
        #插入用户信息
        user_id= values[0][0]
        print("user_id="+str(user_id))
        sql = 'insert into usr_base_info(user_id, email, phone, nickname) values(\'%s\', \'%s\', \'%s\', \'%s\')' \
              % (user_id, usr.usr_email, usr.usr_phone, usr.usr_nickname)
        self.execute_insert(sql)
        return user_id


    def to_string(self):
        return 'data_base: %s, usr_name: %s, usr_pwd: %s' % (self.data_base, self.usr_name, self.usr_pwd)

    def get_user_info(self, user_id):
        sql='select * from usr_base_info where user_id = \'%s\'' % (user_id)
        values = self.execute_query(sql)
        return {'user_id':values[0][0], 'cost':values[0][1],'rate':values[0][2],
                'risk':values[0][3],'time':values[0][4],'email':values[0][5],
                'phone':values[0][1], 'avator':values[0][7], 'nickname':values[0][8]}

    def update_user_info(self, user_id, user_name, email, phone, cost, rate, risk, time,avator):
        #首先获取原有的信息
        origin_info=self.get_user_info(user_id)
        if user_name is None:
            user_name=origin_info['nickname']
        if email is None:
            email=origin_info['email']
        if phone is None:
            phone=origin_info['phone']
        if cost is None:
            cost=origin_info['cost']
        if rate is None:
            rate=origin_info['rate']
        if risk is None:
            risk=origin_info['risk']
        if time is None:
            time=origin_info['time']
        if avator is None:
            avator=origin_info['avator']
        print('user_name=%s, email=%s, phone=%s, cost=%s, rate=%s, risk=%s, time=%s, avator=%s' %(user_name, email, phone, cost, rate, risk, time, avator))
        sql='update usr_base_info set nickname=\'%s\', email=\'%s\', phone=\'%s\', ' \
            'cost=\'%s\', rate=\'%s\', risk=\'%s\', time=\'%s\', avator=\'%s\' where user_id=\'%s\'' \
            % (user_name, email, phone, cost, rate, risk, time, avator, user_id)
        self.execute_update(sql)
        return self.get_user_info(user_id)



# test
if __name__ == "__main__":
    user_dao = User_DAO()
    print(user_dao.to_string())
    user_dao.do_login('admin', 'admin')
    user_dao.do_login('admin', 'admin1')
